package com.temp.config;

import com.temp.filter.CustomAuthenticationFilter;
import com.temp.realm.MyShiroRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.crazycake.shiro.RedisManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host:127.0.0.1}")
    private String host;

    @Value("${spring.redis.port:6379}")
    private String port;

    @Value("${spring.redis.password:AABB@1122}")
    private String password;

    @PostConstruct
    public void init() {
        log.info("redis连接信息:主机{},端口{},密码{}", host, port, password);
    }

    // ==================== 1. Redis 配置 ====================
    @Bean
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host + ":" + port); // Redis 地址
        redisManager.setTimeout(2000); // 连接超时（毫秒）
        redisManager.setPassword(password); // 无密码可删除
        return redisManager;
    }

    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        redisSessionDAO.setKeyPrefix("shiro:session:"); // Redis key 前缀
        redisSessionDAO.setExpire(1800); // Session 过期时间（秒，30分钟）
        return redisSessionDAO;
    }

    // ==================== 2. Session 管理 ====================
    @Bean
    public SimpleCookie sessionIdCookie() {
        SimpleCookie cookie = new SimpleCookie("JSESSIONID");
        cookie.setHttpOnly(true); // 防止 XSS
        cookie.setPath("/");      // Cookie 作用路径
        cookie.setMaxAge(-1);     // 浏览器关闭时过期
        return cookie;
    }

    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO()); // 使用 Redis 存储
        sessionManager.setGlobalSessionTimeout(1800000);  // 30分钟（毫秒）
        sessionManager.setSessionValidationSchedulerEnabled(true);
        sessionManager.setSessionIdCookieEnabled(true);
        sessionManager.setSessionIdCookie(sessionIdCookie()); // 自定义 Cookie
        sessionManager.setSessionIdUrlRewritingEnabled(false); // 禁用 URL 重写
        return sessionManager;
    }

    // ==================== 3. SecurityManager ====================
    @Bean
    public SessionsSecurityManager securityManager(MyShiroRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setSessionManager(sessionManager()); // 关键！替换 SessionManager
        return securityManager;
    }

    // ==================== 4. Shiro 过滤器 ====================
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 自定义过滤器
        Map<String, Filter> filters = new LinkedHashMap<>();
        filters.put("authc", new CustomAuthenticationFilter());
        shiroFilterFactoryBean.setFilters(filters);

        // 拦截规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 1. 首先，设置所有的【认证相关API】为匿名访问（白名单）
        filterChainDefinitionMap.put("/api/user/login", "anon");
        filterChainDefinitionMap.put("/api/user/register", "anon");
        filterChainDefinitionMap.put("/api/user/forgetPW", "anon");
//        filterChainDefinitionMap.put("/api/user/r-captcha", "anon");
//        filterChainDefinitionMap.put("/api/user/rs-captcha", "anon");
        filterChainDefinitionMap.put("/api/campaign/random", "anon");
        filterChainDefinitionMap.put("/api/language/query", "anon");
        filterChainDefinitionMap.put("/api/system/query", "anon");
        filterChainDefinitionMap.put("/api/payment/notify", "anon");

        // 2. 然后，设置所有的【静态资源】为匿名访问（白名单）
        filterChainDefinitionMap.put("/error", "anon");
//        filterChainDefinitionMap.put("/doc.html", "anon");
//        filterChainDefinitionMap.put("/v2/api-docs", "anon");
//        filterChainDefinitionMap.put("/swagger-resources", "anon");
//        filterChainDefinitionMap.put("/webjars/**", "anon");

        filterChainDefinitionMap.put("/app/**", "anon");
        filterChainDefinitionMap.put("/icons/default/**", "anon");
        filterChainDefinitionMap.put("/models/dom/**", "anon");
        filterChainDefinitionMap.put("/plugins/**", "anon");
        filterChainDefinitionMap.put("/skins/**", "anon");
        filterChainDefinitionMap.put("/tailwindcss/**", "anon");
        filterChainDefinitionMap.put("/themes/silver/**", "anon");

        filterChainDefinitionMap.put("/api/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    // ==================== 5. Realm 和凭证匹配器 ====================
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm realm = new MyShiroRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        return realm;
    }

    // ==================== 6. 支持 AOP 注解 ====================
    @Bean
    public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}